<template>
  <div :class="$style.wrapper">
    <slot name="queryForm">
      <el-form
        :model="tableData.queryParams"
        ref="queryForm"
        label-width="120px"
      >
        <el-collapse accordion style="min-width: 1000px">
          <el-collapse-item>
            <template #title>
              <div
                style="display: grid; grid-template-columns: 1fr 1fr 1fr 1fr"
              >
                <el-form-item
                  v-for="(field, idx) in _queryFields[0]"
                  :key="idx"
                  :label="field.label"
                  :prop="field.prop"
                >
                  <slot
                    v-bind="{ data: tableData.queryParams, field }"
                    :name="'query-' + field.prop"
                  >
                    <el-input
                      v-model="tableData.queryParams[field.prop]"
                      clearable
                      :placeholder="'请输入' + field.label"
                      @keyup.space.stop.native
                      @keyup.enter.stop.native="handleQuery"
                      @click.stop.native
                    />
                  </slot>
                </el-form-item>
              </div>
              <div style="padding: 0px 15px; flex: 0 0 190px">
                <el-button type="primary" @click.stop.native="handleQuery"
                  ><el-icon> <Search /> </el-icon>搜索</el-button
                >
                <el-button :icon="Refresh" @click.stop.native="resetQuery"
                  >重置</el-button
                >
              </div>
            </template>
            <div
              :class="$style.hidebox"
              v-for="idx in _queryFields.length - 1"
              :key="idx"
            >
              <el-form-item
                v-for="(field, idx2) in _queryFields[idx]"
                :key="idx2"
                :label="field.label"
                :prop="field.prop"
              >
                <slot
                  v-bind="{ data: tableData.queryParams, field }"
                  :name="'query-' + field.prop"
                >
                  <el-input
                    v-model="tableData.queryParams[field.prop]"
                    clearable
                    :placeholder="'请输入' + field.label"
                    @keyup.space.stop.native
                    @keyup.enter.stop.native="handleQuery"
                  />
                </slot>
              </el-form-item>
            </div>
          </el-collapse-item>
        </el-collapse>
      </el-form>
    </slot>
    <el-row :gutter="10" class="mb8" style="margin-top: 10px">
      <el-col :span="24" style="text-align: right">
        <slot name="actionButton" v-bind="{ tableData, tableDataChild }">
          <div v-if="!readOnly">
            <span style="padding-left: 10px">
              <el-button
                v-if="disabledBtns.includes('add') === false"
                type="primary"
                plain
                @click="() => handleAdd(tableData)"
                v-hasPermi="[modulePermi + ':add']"
              >
                <el-icon><Plus /></el-icon>
                新增
              </el-button>

              <!-- <el-button type="success" plain icon="el-icon-edit" size="mini" @click="handleEditTabl" v-hasPermi="['marketing:customer:edit']">
            修改
          </el-button> -->

              <el-button
                v-if="disabledBtns.includes('delete') === false"
                type="danger"
                plain
                icon="el-icon-delete"
                size="mini"
                @click="handleDelete"
                :disabled="!isSelected || readOnlyChild"
                v-hasPermi="[modulePermi + ':remove']"
              >
                删除
              </el-button>
            </span>
            <span
              style="padding-left: 10px"
              v-if="disabledBtns.includes('export') === false"
            >
              <el-button
                style="padding-left: 10px"
                type="warning"
                plain
                icon="el-icon-download"
                size="mini"
                @click="exportXls()"
                >导出</el-button
              >
            </span>
            <span style="padding-left: 10px"
              ><slot
                name="actionButtonInner"
                v-bind="{ tableData, tableDataChild }"
              ></slot
            ></span>
          </div>
        </slot>
      </el-col>
    </el-row>
    <!-- 主表信息 -->
    <div style="height: 100%; display: flex; flex-direction: column">
      <el-table
        :cell-style="cellStyle"
        highlight-current-row
        border
        stripe
        ref="multipleTable"
        v-loading="tableData.loading"
        :data="tableData.rows"
        @row-click="getListChild"
        @select="handleSelect"
        @selection-change="handleSelectionChange"
        :show-summary="tableData.summary"
        :summary-method="summaryMethod"
        :height="tableData.height"
        use-virtual
        show-body-overflow="title"
        show-header-overflow="title"
        row-id="id"
        row-key="id"
        :row-height="30"
        :current-row-key="curRow.id"
        :header-cell-style="{ 'text-align': 'center' }"
      >
        <template v-for="column in _columns" :key="column.prop">
          <el-table-column
            :label="column.label"
            :prop="column.prop"
            :type="column.type"
            :align="column.align"
            :width="column.width"
            :fixed="column.fixed"
            :formatter="column.formatter"
            :sortable="column.sortable"
            :min-width="column.minWidth"
            :selectable="column.selectable"
            :class-name="$style.tdCell"
            show-overflow-tooltip
          >
            <template
              v-slot="scope"
              v-if="
                !column.formatter &&
                column.type !== 'index' &&
                column.type !== 'selection'
              "
            >
              <slot v-bind="scope" :name="column.prop">
                <span>{{ scope.row[column.prop] }}</span>
              </slot>
            </template>
          </el-table-column>
        </template>
        <slot name="operate" v-bind="{ tableData, tableDataChild }">
          <el-table-column
            v-if="!readOnly"
            label="操作"
            width="120"
            fixed="right"
            :show-overflow-tooltip="true"
            align="center"
          >
            <template #default="scope">
              <div v-if="scope.row.state == 0">
                <slot name="operation" v-bind="scope">
                  <el-button
                    link
                    @click="handleEditTable(scope.row)"
                    v-hasPermi="[modulePermi + ':edit']"
                  >
                    <el-icon><Edit /></el-icon> 编辑
                  </el-button>
                  <el-button
                    link
                    @click="handleDelete(scope.row)"
                    v-hasPermi="[modulePermi + ':remove']"
                    ><el-icon><Delete /></el-icon>
                    删除
                  </el-button>
                </slot>
              </div>
            </template>
          </el-table-column>
        </slot>
      </el-table>
      <div
        style="
          padding: 5px;
          background-color: white;
          text-align: right;
          width: 100%;
          display: flex;
          justify-content: flex-end;
        "
      >
        <slot name="sumnumber" v-bind="{ tableData, tableDataChild }"></slot>
        <el-pagination
          :current-page.sync="tableData.queryParams.pageNum"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :page-sizes="[5, 10, 20, 30, 40]"
          :page-size="tableData.queryParams.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="tableData.total"
        ></el-pagination>
      </div>

      <!-- 子表信息 -->
      <div v-if="hasTabs">
        <slot name="childTable">
          <div style="position: relative">
            <div
              v-show="tableData.form[relationCode]"
              :class="$style.childsearch"
            >
              <el-input
                placeholder="请输入关键字查询"
                prefix-icon="el-icon-search"
                size="small"
                v-model="serachFuzzy"
              ></el-input>
              <div v-if="!readOnly && !readOnlyChild">
                <slot
                  name="childTableToolbar"
                  v-bind="{ tableData, tableDataChild }"
                >
                  <!--                  <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddChild" v-hasPermi="[modulePermi + ':add']">
                    新增明细
                  </el-button>-->
                </slot>
              </div>
            </div>
            <el-tabs v-model="activeName">
              <el-tab-pane label="明细数据" name="first" v-if="hasChild">
                <el-table
                  highlight-current-row
                  border
                  stripe
                  use-virtual
                  show-body-overflow="title"
                  show-header-overflow="title"
                  row-id="id"
                  row-key="id"
                  :row-height="30"
                  :data="filterFuzzy"
                  :show-summary="tableDataChild.summary"
                  :summary-method="getSummaries"
                  :total-option="tableDataChild.totalOption"
                  :height="tableDataChild.height"
                  :header-cell-style="{ 'text-align': 'center' }"
                >
                  <template v-for="column in _columnsChild" :key="column.prop">
                    <u-table-column
                      :label="column.label"
                      :prop="column.prop"
                      :type="column.type"
                      :align="column.align"
                      :width="column.width"
                      :fixed="column.fixed"
                      :formatter="column.formatter"
                      :sortable="column.sortable"
                      :min-width="column.minWidth"
                      :selectable="column.selectable"
                      :class-name="$style.tdCell"
                      show-overflow-tooltip
                    >
                      <template
                        v-slot="scope"
                        v-if="
                          !column.formatter &&
                          column.type !== 'index' &&
                          column.type !== 'selection'
                        "
                      >
                        <slot v-bind="scope" :name="column.prop">
                          <span>{{ scope.row[column.prop] }}</span>
                        </slot>
                      </template>
                    </u-table-column>
                  </template>
                  <!--                  <u-table-column
                    v-if="!readOnly && !readOnlyChild"
                    label="操作"
                    width="120"
                    fixed="right"
                    :show-overflow-tooltip="true"
                    align="center">
                    <template #default="scope">
                      <slot name="operationChild" v-bind="scope">
                        <el-button
                          type="text"
                          size="small"
                          icon="el-icon-edit"
                          @click="handleEditChild(scope.row)"
                          v-hasPermi="[modulePermi + ':edit']">
                          编辑
                        </el-button>
                        <el-button
                          type="text"
                          size="small"
                          icon="el-icon-delete"
                          @click="handleDeleteChild(scope.row)"
                          v-hasPermi="[modulePermi + ':remove']">
                          删除
                        </el-button>
                      </slot>
                    </template>
                  </u-table-column>-->
                </el-table>
              </el-tab-pane>

              <el-tab-pane
                v-for="tab in extTabs"
                :label="tab.label"
                :name="tab.name"
              >
                <el-table-v2
                  v-if="['check'].includes(tab.name)"
                  :ref="tab.name"
                  show-overflow="title"
                  show-header-overflow="title"
                  :data="dataCheck"
                  :columns="columnCheck"
                  widthResize
                  :highlight-current-row="false"
                ></el-table-v2>
                <el-table-v2
                  v-if="['change'].includes(tab.name)"
                  :ref="tab.name"
                  show-overflow="title"
                  show-header-overflow="title"
                  :data="dataChange"
                  :columns="columnChange"
                  widthResize
                  :highlight-current-row="false"
                ></el-table-v2>
                <slot
                  :name="tab.name"
                  v-bind="{ tableData, tableDataChild }"
                ></slot>
              </el-tab-pane>
            </el-tabs>
          </div>
          <!-- 添加或修改子表对话框 -->
          <el-dialog
            :title="tableDataChild.title"
            v-model="tableDataChild.open"
            :close-on-click-modal="false"
            draggable
            :width="dialogwidth"
            append-to-body
          >
            <slot name="formChild" v-bind="{ tableDataChild }">
              <el-form
                ref="formChild"
                :model="tableDataChild.form"
                :rules="tableDataChild.rules"
                label-width="120px"
              >
                <slot
                  name="formitemChild"
                  v-bind="{ form: tableDataChild.form }"
                >
                  <el-form-item
                    v-for="(field, idx) in _fieldsChild"
                    :key="idx"
                    :label="field.label"
                    :prop="field.prop"
                  >
                    <template>
                      <slot
                        v-bind="{ data: tableDataChild.form, field }"
                        :name="'formChild-' + field.prop"
                      >
                        <el-input
                          v-model="tableDataChild.form[field.prop]"
                          :placeholder="'请输入' + field.label"
                          :disabled="field.disabled"
                        />
                      </slot>
                    </template>
                  </el-form-item>
                </slot>
              </el-form>
              <div slot="footer" class="dialog-footer">
                <el-button @click="cancelDiag(tableDataChild)">关 闭</el-button>
                <el-button type="primary" @click="submitFormChild"
                  >保 存</el-button
                >
              </div>
            </slot>
          </el-dialog>
        </slot>
      </div>
    </div>
    <!-- 新增修改对话框 -->
    <el-dialog
      :title="tableData.title"
      v-model="tableData.open"
      :close-on-click-modal="false"
      draggable
      :width="dialogwidth"
      append-to-body
    >
      <slot
        name="form"
        v-if="tableData.open"
        v-bind="{ tableData, tableDataChild }"
      >
        <el-form
          ref="form"
          :model="tableData.form"
          :rules="tableData.rules"
          :label-width="dialogLabelWidth"
          :inline="inline"
        >
          <slot name="formitem" v-bind="{ form: tableData.form }">
            <el-form-item
              v-for="(field, idx) in _fields"
              :key="idx"
              :label="field.label"
              :prop="field.prop"
            >
              <template>
                <slot
                  v-bind="{ data: tableData.form, field }"
                  :name="'form-' + field.prop"
                >
                  <el-input
                    v-model="tableData.form[field.prop]"
                    :placeholder="
                      field.disabled ? '自动生成' : '请输入' + field.label
                    "
                    :disabled="field.disabled"
                  />
                </slot>
              </template>
            </el-form-item>
          </slot>
        </el-form>

        <div class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
      </slot>
    </el-dialog>
  </div>
</template>
<script>
import BaseService from "@/api/base/base";
import { splitArray } from "@/utils/ruoyi";
// let baseService = new BaseService('base')
// import * as flowService from '@/api/system/flow'

export default {
  name: "HdTablePage",
  model: {
    prop: "value",
    event: "change",
  },
  props: {
    /**
     * 控制子dialog弹框宽度
     */
    dialogwidth: {
      type: String,
      default: "800px",
    },
    /**
     * 控制子dialog弹框中文本长度
     */
    dialogLabelWidth: {
      type: String,
      default: "120px",
    },
    /**
     * form表单开启行内
     */
    inline: {
      type: Boolean,
      default: false,
    },
    /**
     * 字表的值，{key:value}的格式
     */
    value: {
      type: Array,
      default: () => [],
    },
    /**
     * 禁用的功能按钮
     */
    disabledBtns: {
      type: Array,
      default: () => [],
    },
    /**
     * 字表的字段属性
     */
    defaultData: {
      type: Object,
      default: () => {
        return {
          form: {},
          queryParams: {},
          rules: {},
        };
      },
    },
    cellStyle: {
      type: Function,
    },
    /**
     * 是否只读
     */
    readOnly: {
      type: Boolean,
      default: false,
    },
    /**
     * 子表关联编号
     */
    relationCode: {
      type: String,
      default: "",
    },
    modulePath: {
      type: String,
      default: "",
    },
    /**
     * 自定义子表列属性,如[{dataIndex:'shuxingmingzi15',width:'120px'}],8.0.4及以后版本支持
     */
    columns: {
      type: Array,
      default: () => [],
    },
    columnsChild: {
      type: Array,
      default: () => [],
    },
    extTabs: {
      type: Array,
      default: () => [],
    },
    /**
     * 某行是否可选
     * @since 8.0.11
     */
    showSelection: {
      type: Function,
      default: () => true,
    },
    /**
     * 删除时执行函数
     * @since 8.0.11
     */

    width: {
      type: String,
      default: "50%",
    },
    height: {
      type: [String, Number],
      default: document.body.clientHeight - 290,
    },
  },
  data() {
    return {
      baseService: new BaseService(this.modulePath),
      activeName: "first",
      modulePermi: "",
      loading: false,
      exportLoading: false,
      curRow: {},
      serachFuzzy: "",
      tableData: {
        title: "",
        height: 0, //document.body.clientHeight - 200,
        rows: [],
        loading: false,
        total: 0,
        selection: [],
        open: false,
        form: {
          createBy: undefined,
          createTime: undefined,
          version: undefined,
          state: undefined,
        },
        queryParams: {
          pageNum: 1,
          pageSize: 20,
          state: null,
          createBy: null,
          // params: {
          //   beginDate: this.$moment().startOf('month').format(),
          //   endDate: this.$moment().endOf('month').format(),
          // },
        },
        rules: {},
        childList: [],
      },
      tableDataChild: {
        height: 0,
        rows: [],
        loading: false,
        total: 0,
        open: false,
        form: {},
        summary: false,
        totalOption: [],
        selection: [],
        rules: {},
        queryParams: {
          pageNum: 1,
          pageSize: 9999,
        },
      },
      disabled: true,
      readOnlyChild: false,
      dataCheck: [],
      dataChange: [],
      columnCheck: [
        { title: "序号", type: "index", width: "50px", align: "center" },
        { title: "审批部门", field: "deptBy", width: "150px" },
        { title: "审批人", field: "checkBy", width: "150px" },
        {
          title: "审批状态",
          field: "state",
          width: "100px",
          formatter({ row }) {
            return row.state == 0
              ? "待审批"
              : row.state == 1
              ? "已同意"
              : row.state == 2
              ? "已驳回"
              : "审批中";
          },
        },
        { title: "审批时间", field: "endTime", width: "150px" },
        { title: "审批内容", field: "content" },
      ],
      columnChange: [
        { title: "修改时间", field: "changeTime", width: "150px" },
        { title: "修改人", field: "changeBy", width: "150px" },
        { title: "修改内容", field: "content" },
      ],
    };
  },
  created() {
    this._fields
      .filter((o) => o.required || o.rule)
      .forEach((element) => {
        if (element.rule) {
          this.tableData.rules[element.prop] = element.rule;
        } else {
          this.tableData.rules[element.prop] = {
            required: true,
            message: "请输入" + element.label,
            trigger: ["blur", "change"],
          };
        }
      });
    // Object.assign(this.tableData.queryParams, this.defaultData.queryParams)
    this.tableData.queryParams = { ...this.defaultData.queryParams };
    const colsum = this.columns.filter((o) => o.summary);
    this.tableData.summary = colsum.length > 0;
    this.tableData.totalOption = colsum;
    this.tableData.totalRow = [];
    if (this.hasTabs) {
      if (this.extTabs.length > 0) {
        this.activeName = this.extTabs[0].name;
      }
      this.tableData.height = this.height / 2;
      this.tableDataChild.height = this.height / 2;
    } else {
      this.tableData.height = this.height;
    }
    if (this.hasChild) {
      this.activeName = "first";
      const colsum = this.columnsChild.filter((o) => o.summary);
      this.tableDataChild.summary = colsum.length > 0;
      this.tableDataChild.totalOption = colsum;
    }

    this.modulePermi = this.modulePath.replaceAll("/", ":");
    this.getList();
  },
  computed: {
    isSelected() {
      return this.tableData.selection.length > 0;
    },
    hasChild() {
      return this.columnsChild.length > 0;
    },
    hasTabs() {
      return this.columnsChild.length > 0 || this.extTabs.length > 0;
    },
    filterFuzzy() {
      let searchData = this.tableDataChild.rows;
      this.serachFuzzy = this.serachFuzzy.trim();
      if (this.serachFuzzy) {
        searchData = searchData.filter((o) => {
          return JSON.stringify(o).indexOf(this.serachFuzzy) !== -1;
        });
      }
      return searchData;
    },
    _columns() {
      return this.columns
        .filter((a) => !(a.isColumn === false))
        .map((a) => {
          if (["selection", "index"].includes(a.type)) {
            if (!a.align) a.align = "center";
            if (!a.label) a.label = "#";
          }
          return a;
        });
    },
    _columnsChild() {
      return this.columnsChild
        .filter((a) => !(a.isColumn === false))
        .map((a) => {
          if (["selection", "index"].includes(a.type)) {
            if (!a.align) a.align = "center";
            if (!a.label) a.label = "#";
          }
          return a;
        });
    },
    _fields() {
      let tmpArr = this.columns.filter(
        (a) => !a.type && !(a.isField === false)
      );
      if (this.tableData.title === "修改") {
        tmpArr = tmpArr.map((o) => {
          let a = { ...o };
          if (a.disabledEdit === true) {
            a.disabled = true;
          }
          return a;
        });
      }
      return tmpArr;
    },
    _fieldsChild() {
      return this.columnsChild.filter((a) => !a.type && !(a.isField === false));
    },
    _queryFields() {
      const tmpArr = this.columns.filter(
        (a) => !a.type && !(a.isSearch === false)
      );
      return splitArray(tmpArr, 4);
    },
  },
  methods: {
    /** 查询客户列表 */
    getList(refresh = true) {
      this.tableData.loading = true;
      if (refresh) this.tableData.queryParams.pageNum = 1;
      this.baseService.getList(this.tableData.queryParams).then((response) => {
        this.$emit("refresh", response);
        this.tableData.rows = response.rows;
        this.tableData.total = response.total;
        this.tableData.loading = false;
        this.tableData.totalNumbers = response.totalNumbers;
        if (response.totalNumbers && response.totalNumbers.length > 0) {
          let i = 0;
          this.tableData.totalRow = this._columns.map((o, idx) => {
            if (idx == 0) return "合计";
            if (o.summary) {
              return response.totalNumbers[i++];
            } else {
              return "";
            }
          });
        } else {
          this.tableData.summary = false;
        }
        // if (!this.hasChild) return
        if (this.tableData.rows[0]) {
          this.$nextTick(() => {
            // TODO
            // const pxdata = this.$refs.multipleTable.getUTreeData();
            // this.$refs.multipleTable.toggleRowSelection([{ row: pxdata[0] }]);
          });

          this.getListChild(this.tableData.rows[0]);
        } else {
          this.tableDataChild.rows = [];
        }
      });
    },
    handleCurrentChange(res) {
      this.tableData.queryParams.pageNum = res;
      this.load();
    },
    handleSizeChange(res) {
      this.tableData.queryParams.pageSize = res;
      this.handleQuery();
    },
    load() {
      //if (this.tableData.queryParams.pageNum < Math.ceil(this.tableData.total / this.tableData.queryParams.pageSize)) {
      // this.tableData.queryParams.pageNum++
      this.baseService.getList(this.tableData.queryParams).then((response) => {
        this.tableData.rows = response.rows;
        this.tableData.total = response.total;
        this.tableData.loading = false;
      });
      // }
      // return 0
    },
    async getListChild(row) {
      if (this.curRow == row) return;
      //点击行触发，选中或不选中复选框
      if (row) {
        //this.$nextTick(() => {
        this.$refs.multipleTable.clearSelection();
        this.$refs.multipleTable.toggleRowSelection([{ row }]);
        //this.$refs.multipleTable.setCurrentRow(row)
        // })
        this.curRow = row;
        this.readOnlyChild = row.state != 0;
      }
      row = row || this.tableData.form;
      this.tableData.form = Object.assign({}, row);
      this.$emit("rowClick", this.tableData.form);
      if (row && row.id && this.hasChild) {
        this.tableDataChild.loading = true;
        const tmp = { ...row };
        delete tmp.state;
        this.extTabs.forEach((tab) => {
          if (tab.name == "check") {
            // flowService.listCheck({ orderCode: this.tableData.form[this.relationCode] }).then((res) => {
            //   // tab.column = this.columnCheck
            //   this.dataCheck = res.rows
            // })
          }
          if (tab.name == "change") {
            // flowService.listChange({ orderCode: this.tableData.form[this.relationCode] }).then((res) => {
            //   // tab.column = this.columnChange
            //   this.dataChange = res.rows
            // })
          }
        });
        await this.baseService.getListChild(tmp).then((response) => {
          this.tableDataChild.rows = response.data;
          this.tableDataChild.loading = false;
        });
      } else {
        this.tableDataChild.rows = [];
      }
    },
    // 取消按钮
    cancel() {
      this.tableData.open = false;
    },
    test(param) {
      const { columns, data } = param;
    },
    /** 搜索按钮操作 */
    handleQuery(query) {
      this.tableData.queryParams = { ...this.tableData.queryParams, ...query };
      this.getList();
    },
    exportXls() {
      this.$confirm("是否确认导出?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.exportLoading = true;
          return this.baseService.export(this.tableData.queryParams);
        })
        .then((response) => {
          this.download(response.msg);
          this.exportLoading = false;
        });
    },
    /** 修改按钮操作 */
    async handleEditTable(row, opt) {
      this.resetForm("form");
      const ids =
        row?.id || this.tableData.form.id || this.tableData.selection[0].id;
      await this.getListChild(row);
      if (!opt) {
        this.baseService.getDetail(ids).then((response) => {
          this.tableData.open = true;
          this.tableData.title = "修改";
          if (response) this.tableData.form = response.data;
          else this.tableData.form = row;
          this.$emit("rowEdit", this.tableData);
        });
      } else {
        this.tableData.form = row;
        this.tableData.open = true;
      }
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      let ids;
      if (row.id) {
        ids = row.id;
      } else {
        ids = this.tableData.selection.map((item) => item.id);
        if (ids.length === 0) ids = this.tableData.form.id;
      }

      this.$confirm("是否确认删除选中的数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          return this.baseService.delete(ids);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        });
    },
    handleSelect(selection, row) {
      // this.$refs.multipleTable.$refs.singleTable.$children[17].handleClick({}, row)
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      // this.$refs.multipleTable.clearSelection()
      // this.getListChild(selection[selection.length - 1])
      this.tableData.selection = selection;
    },

    /** 新增按钮操作 */
    handleAdd(data) {
      data.form = { ...this.defaultData.form };
      this.resetForm("form");
      data.open = true;
      data.title = "添加";
    },
    // 取消按钮
    cancelDiag(data) {
      data.open = false;
    },
    setForm(data, type) {
      this.tableData.form = { ...this.tableData.form, ...data };
    },
    setFormChild(data) {
      this.tableDataChild.form = { ...this.tableDataChild.form, ...data };
    },
    resetQuery() {
      this.resetForm("queryForm");
      this.$emit("resetQuery", this.tableData.queryParams);
      this.tableData.queryParams = { ...this.defaultData.queryParams };
      this.tableData.queryParams.params = this.defaultData.queryParams
        ? { ...this.defaultData.queryParams.params }
        : null;

      this.handleQuery();
    },
    /** 提交按钮 */
    submitForm() {
      this.tableData.childList = this.tableDataChild.rows;
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.tableData.form.id != null) {
            this.baseService.save(this.tableData.form).then(() => {
              this.msgSuccess("修改成功");
              this.tableData.open = false;
              this.getList();
            });
          } else {
            this.baseService.add(this.tableData.form).then(() => {
              this.msgSuccess("新增成功");
              this.tableData.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 新增按钮操作 */
    handleAddChild() {
      this.resetForm("formChild");
      this.tableDataChild.form[this.relationCode] =
        this.tableData.form[this.relationCode];
      // this.tableDataChild.form = this.tableData.form
      this.tableDataChild.title = "新增明细";
      this.$emit("getlists", this.tableData.form);
      this.tableDataChild.open = true;
    },
    handleEditChild(data) {
      this.tableDataChild.open = true;
      this.tableDataChild.title = "修改明细";
      this.tableDataChild.form = Object.assign({}, data);
      this.$emit("getEdit", data);
    },
    handleSaveChild(row) {
      this.baseService.saveChild(row).then((res) => {
        this.msgSuccess("保存成功");
      });
    },
    handleCancelChild(row) {
      row.rwdMoney = row.tmpJe;
    },
    handleDeleteChild(data) {
      this.$confirm("是否确认删除选中的数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        this.baseService.deleteChild([data.id]).then((res) => {
          this.getListChild();
          this.msgSuccess("删除成功");
        });
      });
    },
    /** 提交字表按钮 */
    submitFormChild() {
      this.$refs["formChild"].validate((valid) => {
        if (valid) {
          if (this.tableDataChild.form.id != null) {
            this.baseService.saveChild([this.tableDataChild.form]).then(() => {
              this.msgSuccess("修改成功");
              this.tableDataChild.open = false;
              this.getListChild();
            });
          } else {
            this.baseService.addChild([this.tableDataChild.form]).then(() => {
              this.msgSuccess("新增成功");
              this.tableDataChild.open = false;
              this.getListChild();
            });
          }
        }
      });
    },
    // 合计的方法
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = this.sumText;
          return;
        }
        const values = data.map((item) => Number(item[column.property]));
        // 需要合并的选项
        const flas = this.tableDataChild.totalOption.filter(
          (item) => item.label === column.label
        );
        const precisions = [];
        let notNumber = true;
        values.forEach((value) => {
          if (!isNaN(value)) {
            notNumber = false;
            let decimal = ("" + value).split(".")[1];
            precisions.push(decimal ? decimal.length : 0);
          }
        });
        const precision = Math.max.apply(null, precisions);
        if (!notNumber && flas.length > 0) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return parseFloat((prev + curr).toFixed(Math.min(precision, 20)));
            } else {
              return prev;
            }
          }, 0);
          sums[index] += flas[0].unit || "";
        } else {
          sums[index] = "";
        }
      });
      // 返回一个二维数组的表尾合计
      return [sums];
    },
    summaryMethod({ columns, data }) {
      // 返回一个二维数组的表尾合计(不要平均值，你就不要在数组中添加)
      return [this.tableData.totalRow];
    },
  },
  provide() {
    return {
      hdTable: this,
    };
  },
};
</script>
<style module lang="scss">
.wrapper {
  :global {
    .el-collapse-item__content {
      padding-bottom: 0px;
    }
    .el-form-item {
      margin-bottom: 0px;
    }
    .el-collapse-item__header {
      padding: 25px 0px;
      > div {
        flex: 1 1 25%;
      }
    }
  }

  .hidebox {
    display: grid;
    padding-bottom: 10px;
    grid-template-columns: 1fr 1fr 1fr 1fr;
    width: calc(100% - 210px);
  }
}
.childsearch {
  display: flex;
  padding: 5px;
  position: absolute;
  right: 0px;
  width: 400px;
  z-index: 9;
  div + div {
    padding-left: 10px;
  }
}
.hdDivButton {
  button {
    width: calc(50% - 5px);
  }
}
.tdCell {
  > div > span {
    padding-left: 5px;
  }
}
</style>
